// 源插件
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import {
  NumberDivide,
  DateDiff,
  FormatnumberZero,
  Mover,
  DateStamp,
  numMulti,
} from '@/function.js';

// 视图插件
import {
  BackTop,
  Empty,
  Spin,
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Upload,
  Popconfirm,
} from 'antd';
import TimelineChartSeven from '@/components/Charts/TimelineChartSeven';

// 外部组件
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Loading from '@/components/Loading/Loading';
import $ from 'jquery';
import BondsChart from './BondsChart';

import BillUpload from './BillUpload';
// css OR less预编译器
import styles from './bonds.less';
import KlineEchartsForeign from '../../../components/KlineEcharts/KlineEchartsForeign';

// 图片

/**
 *  Describe:数据连接
 *  Created by xjc on 2019/5/15
 */

@connect(({ bonds, loading }) => ({
  bonds,
  loading: loading.models.bondsRule,
}))
@Form.create()
class NewTwoPosition extends PureComponent {
  componentWillMount() {}

  state = {
    listLoading: false, // 加载状态
    selectedRows: [], // 选择行
    formValues: {
      num: 10,
      page: 1,
    }, // 表格参数
    /* pageValues:{current: 1, pageSize: 10, total: 0}, */
    kVisible: false, // modal开关
    tVisible: false, // modal开关
    symbol: 'US.BABA',
    record: {}, // 当前行内容
    searchText: '', // 搜索内容
    columns: [], // 表头处理结果
    currentDataSource: [], // 表剩余数据
    chart: {},
    codes: '',
    BillUploadVisible: false, // modal开关
    isUpdate: false,
    ric: '',
    chartVisible: false,
    chartTitle: '',
  };

  /**
   *  Describe:本地搜索
   *  Created by xjc on 2019/6/4
   */

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={node => {
            this.searchInput = node;
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm)}
          icon="search"
          size="small"
          style={{ width: 80, marginRight: 8 }}
        >
          搜索
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 80 }}>
          重置
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{ color: filtered ? '#1880ff' : '#181816', fontWeight: '700' }} />
    ),
    onFilter: (value, record) => {
      if (record.bondTypeToDisplay === '合计') {
        return true;
      }
      return record[dataIndex] === null
        ? ''
        : record[dataIndex]
            .toString()
            .toLowerCase()
            .includes(value.toLowerCase());
    },
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select());
      }
    },
    render: text => <span>{text}</span>,
  });

  handleSearch = (selectedKeys, confirm) => {
    confirm();
    this.setState({ searchText: selectedKeys[0] });
  };

  handleReset = clearFilters => {
    clearFilters();
    this.setState({ searchText: '' });
  };

  getColumns() {
    const {
      bonds: { bonds },
    } = this.props;
    const typeFilters = bonds.bondTypes.map(item => {
      return {
        text: item,
        value: item,
      };
    });
    return [
      /* {
            title: '序号',
            dataIndex: 'p',
          }, */
      {
        title: '类型',
        dataIndex: 'bondTypeToDisplay',
        align: 'center',
        width: 90,
        // sorter: (a, b) => {
        //   let c = [a.stock, b.stock].sort();
        //   if (c[0] === a.stock) {
        //     return 1;
        //   } else {
        //     return -1;
        //   }
        // },
        filters: typeFilters,
        onFilter: (value, record) => {
          if (record.bondTypeToDisplay === '合计') {
            return true;
          }
          if (record.bondTypeToDisplay !== undefined && record.bondTypeToDisplay) {
            return record.bondTypeToDisplay.includes(value);
          }
        },
        // render: (value, row, index) => {
        //   return (
        //     <span style={{ color: value > 0 ? '#389e0d' : '#e1111e' }}>
        //       {typeof value === 'number' || typeof value === 'string'
        //         ? FormatnumberZero(value, 2).toString() + '%'
        //         : null}
        //     </span>
        //   );
        // },
        onCell: record => ({
          className: styles.newFunction,
        }),
      },
      {
        title: '所属银行',
        dataIndex: 'bank',
        align: 'center',
        width: 120,
        filters: [
          {
            text: '瑞银',
            value: '瑞银',
          },
          {
            text: '中银',
            value: '中银',
          },
          {
            text: '花旗',
            value: '花旗',
          },
        ],
        onFilter: (value, record) => {
          if (record.bondTypeToDisplay === '合计') {
            return true;
          }
          if (record.bank !== undefined && record.bank) {
            return record.bank.includes(value);
          }
        },
        // sorter: (a, b) => {
        //   if (b.stock === '合计') {
        //     return false;
        //   } else {
        //     return a.yieldLeverage - b.yieldLeverage;
        //   }
        // },
        // render: (value, row, index) => {
        //   return (
        //     <span>
        //       {typeof value === 'number' || typeof value === 'string'
        //         ? NumberDivide(value.toString())
        //         : null}
        //     </span>
        //   );
        // },
        className: styles.newFunction,
      },
      {
        title: '名称',
        dataIndex: 'name',
        align: 'center',
        width: 200,
        // sorter: (a, b) => a.name - b.name,
        // render: (value, row, index) => {
        //   return (
        //     <span style={{ color: value > 0 ? '#389e0d' : '#e1111e' }}>
        //       {typeof value === 'number' || typeof value === 'string'
        //         ? FormatnumberZero(value, 2).toString() + '%'
        //         : null}
        //     </span>
        //   );
        // },
        onCell: record => ({
          className: styles.newFunction,
        }),
        ...this.getColumnSearchProps('name'),

        render: (value, row, index) => {
          if (typeof value === 'string') {
            const res = row;
            return (
              <a href="javascript:void(0);" onClick={this.openBondsChart.bind(this, res)}>
                {value}
              </a>
            );
          }
          return null;
        },
      },
      {
        title: '到期日',
        dataIndex: 'duedate',
        align: 'center',
        width: 100,
        render: (value, row, index) => {
          return <span>{typeof value === 'string' ? value.split(' ')[0] : ''}</span>;
        },
        // sorter: (a, b) => a.name - b.name,
        // render: (value, row, index) => {
        //   return (
        //     <span style={{ color: value > 0 ? '#389e0d' : '#e1111e' }}>
        //       {typeof value === 'number' || typeof value === 'string'
        //         ? FormatnumberZero(value, 2).toString() + '%'
        //         : null}
        //     </span>
        //   );
        // },
        onCell: record => ({
          className: styles.newFunction,
        }),
      },
      {
        title: '下一付息日',
        dataIndex: 'nextPaymentDate',
        align: 'center',
        width: 100,
        render: (value, row, index) => {
          return <span>{typeof value === 'string' ? value.split(' ')[0] : ''}</span>;
        },
        // sorter: (a, b) => a.name - b.name,
        // render: (value, row, index) => {
        //   return (
        //     <span style={{ color: value > 0 ? '#389e0d' : '#e1111e' }}>
        //       {typeof value === 'number' || typeof value === 'string'
        //         ? FormatnumberZero(value, 2).toString() + '%'
        //         : null}
        //     </span>
        //   );
        // },
        onCell: record => ({
          className: styles.newFunction,
        }),
      },

      {
        title: '金额/单位',
        dataIndex: 'money',
        align: 'center',
        width: 80,
        sorter: (a, b) => a.money - b.money,
        className: styles.newFunction,
        // render: (value, row, index) => {
        //   return (
        //     <span>
        //       {typeof value === 'number' || typeof value === 'string'
        //         ? NumberDivide((value * 100).toFixed(2).toString()) + '%'
        //         : null}
        //     </span>
        //   );
        // },
      },
      {
        title: '成本价',
        dataIndex: 'costPrice',
        align: 'center',
        width: 80,
        sorter: (a, b) => a.costPrice - b.costPrice,
        className: styles.newFunction,
        render: text => {
          if (typeof text === 'number' || typeof text === 'string') {
            return <span>{FormatnumberZero(numMulti(text, 100), 2)}</span>;
          }
          return null;
        },
      },
      {
        title: '昨日价',
        width: 80,
        dataIndex: 'yesterdayPrice',
        align: 'center',
        sorter: (a, b) => a.yesterdayPrice - b.yesterdayPrice,
        className: styles.newFunction,
        render: text => {
          if (typeof text === 'number' || typeof text === 'string') {
            return <span>{FormatnumberZero(text, 2)}</span>;
          }
          return null;
        },
      },
      {
        title: '今日价',
        width: 80,
        dataIndex: 'todayPrice',
        align: 'center',
        sorter: (a, b) => a.todayPrice - b.todayPrice,
        className: styles.newFunction,
        render: text => {
          if (typeof text === 'number' || typeof text === 'string') {
            return <span>{FormatnumberZero(text, 2)}</span>;
          }
          return null;
        },
      },

      {
        title: '今日市值',
        dataIndex: 'todayMarketValue',
        align: 'center',
        width: 120,
        sorter: (a, b) => a.todayMarketValue - b.todayMarketValue,
        className: styles.newFunction,
        // render: text => {
        //   if (typeof text === 'number' || typeof text === 'string') {
        //     return <span>{FormatnumberZero(text, 2)}</span>;
        //   } else {
        //     return null;
        //   }
        // },
      },

      {
        title: '今日盈亏',
        dataIndex: 'todayProfit',
        align: 'center',
        width: 100,
        sorter: (a, b) => {
          if (b.bondTypeToDisplay === '合计') {
            return false;
          }
          return a.todayProfit - b.todayProfit;
        },
        className: styles.newFunction,
      },
      {
        title: '总盈亏',
        dataIndex: 'totalProfit',
        width: 100,
        align: 'center',
        sorter: (a, b) => {
          if (b.bondTypeToDisplay === '合计') {
            return false;
          }
          return a.totalProfit - b.totalProfit;
        },
        className: styles.newFunction,
      },
      {
        title: '到期收益率',
        dataIndex: 'yieldMaturity',
        align: 'center',
        width: 120,
        sorter: (a, b) => {
          if (b.bondTypeToDisplay === '合计') {
            return false;
          }
          return a.yieldMaturity - b.yieldMaturity;
        },
        render: text => {
          if (typeof text === 'number' || typeof text === 'string') {
            return <span>{`${FormatnumberZero(numMulti(text, 100), 2)}%`}</span>;
          }
          return null;
        },
        className: styles.newFunction,
      },
      {
        title: '杠杆后收益率',
        dataIndex: 'yieldLeverage',
        align: 'center',
        width: 120,
        sorter: (a, b) => {
          if (b.bondTypeToDisplay === '合计') {
            return false;
          }
          return a.yieldLeverage - b.yieldLeverage;
        },
        render: text => {
          if (typeof text === 'number' || typeof text === 'string') {
            return <span>{`${FormatnumberZero(numMulti(text, 100), 2)}%`}</span>;
          }
          return null;
        },
        className: styles.newFunction,
      },
      {
        title: 'ISIN',
        dataIndex: 'isin',
        align: 'center',
        width: 120,
        // sorter: (a, b) => a.isin - b.isin,
        // render: (value, row, index) => {
        //   return (
        //     <span>
        //       {typeof value === 'number' || typeof value === 'string'
        //         ? FormatnumberZero(value, 2).toString()
        //         : null}
        //     </span>
        //   );
        // },
        className: styles.newFunction,
        ...this.getColumnSearchProps('isin'),
      },
      {
        title: '票息',
        dataIndex: 'coupon',
        align: 'center',
        width: 90,
        sorter: (a, b) => a.coupon - b.coupon,
        // render: (value, row, index) => {
        //   return <span>{NumberDivide(value, 2, '%')}</span>;
        // },
        className: styles.newFunction,
      },
      {
        title: 'lv',
        dataIndex: 'lv',
        align: 'center',
        width: 120,
        sorter: (a, b) => {
          if (b.bondTypeToDisplay === '合计') {
            return false;
          }
          return a.lv - b.lv;
        },
        render: text => {
          if (typeof text === 'number' || typeof text === 'string') {
            return <span>{`${FormatnumberZero(numMulti(text, 100), 0)}%`}</span>;
          }
          return null;
        },
        className: styles.newFunction,
      },
      {
        title: '评级',
        dataIndex: 'grade',
        align: 'center',
        width: 80,
        sorter: (a, b) => a.grade - b.grade,
        // render: (value, row, index) => {
        //   return (
        //     <span>
        //       {typeof value === 'number' || typeof value === 'string'
        //         ? NumberDivide(FormatnumberZero(value, 2).toString())
        //         : null}
        //     </span>
        //   );
        // },
        className: styles.newFunction,
      },

      {
        title: '利率',
        dataIndex: 'interestRate',
        align: 'center',
        width: 120,
        sorter: (a, b) => {
          if (b.bondTypeToDisplay === '合计') {
            return false;
          }
          return a.interestRate - b.interestRate;
        },
        render: text => {
          if (typeof text === 'number' || typeof text === 'string') {
            return <span>{`${FormatnumberZero(numMulti(text, 100), 2)}%`}</span>;
          }
          return null;
        },
        className: styles.newFunction,
      },
      {
        title: '今日付息',
        dataIndex: 'todayPayInterest',
        align: 'center',
        width: 120,
        sorter: (a, b) => {
          if (b.bondTypeToDisplay === '合计') {
            return false;
          }
          return a.todayPayInterest - b.todayPayInterest;
        },
        // render: text => {
        //   if (typeof text === 'number' || typeof text === 'string') {
        //     return <span>{FormatnumberZero(text, 2)}</span>;
        //   } else {
        //     return null;
        //   }
        // },
        className: styles.newFunction,
      },
      {
        title: '派息频率',
        dataIndex: 'couponFrequency',
        align: 'center',
        width: 80,

        // render: (text) => {
        //   if (typeof text === 'number' || typeof text === 'string') {
        //     return <span>{FormatnumberZero(text, 2) + "%"}</span>
        //   } else {
        //     return null
        //   }
        // },
        className: styles.newFunction,
      },
      {
        title: '更新周期',
        dataIndex: 'updateFrequency',
        align: 'center',
        width: 80,

        // render: (text) => {
        //   if (typeof text === 'number' || typeof text === 'string') {
        //     return <span>{FormatnumberZero(text, 2) + "%"}</span>
        //   } else {
        //     return null
        //   }
        // },
        className: styles.newFunction,
      },
      // {
      //   title: 'RIC',
      //   dataIndex: 'ric',
      //   align: 'center',
      //   width: 120,

      //   // render: (text) => {
      //   //   if (typeof text === 'number' || typeof text === 'string') {
      //   //     return <span>{FormatnumberZero(text, 2) + "%"}</span>
      //   //   } else {
      //   //     return null
      //   //   }
      //   // },
      //   className: styles.newFunction,
      // },
      {
        title: '操作',

        align: 'center',
        width: 120,

        render: (value, record, index) => {
          const obj = {
            children: value,
            props: {},
          };

          // if (this.indexCountColumns.length > 0) {
          //   let isHave = false;
          //   for (let i = 0; i < this.indexCountColumns.length; i++) {
          //     if (index === this.indexCountColumns[i].index) {
          //       isHave = true;
          //       obj.props.rowSpan = this.indexCountColumns[i].count;
          //     }
          //   }
          //   if (!isHave) {
          //     if (value) {
          //       obj.props.rowSpan = 0;
          //       obj.props.colSpan = 0;
          //     }
          //   }
          // }
          obj.children =
            index > 0 ? (
              <Fragment>
                <Popconfirm
                  title="是否要删除此条？"
                  onConfirm={() => this.handleCurrentData(record)}
                >
                  <a>删除</a>
                </Popconfirm>

                <Divider type="vertical" />
                <a onClick={this.updateCurrentData.bind(this, record)}>修改</a>
              </Fragment>
            ) : (
              <div />
            );
          return obj;
        },
        className: styles.newFunction,
      },
    ];
  }

  handleStandardTableChange = (pagination, filtersArg, sorter, extra) => {
    console.log(extra.currentDataSource, 'extra.currentDataSource');

    const { dispatch } = this.props;
    const { formValues } = this.state;
    this.setState({
      currentDataSource: extra.currentDataSource,
    });
    /* 导入列表数据 */
    dispatch({
      type: 'bonds/GetBonds',
      payload: {
        bondType: 0,
        dataSourceType: 'tableChange',
        currentDataSource: extra.currentDataSource,
      },
      callback: res => {},
    });
  };

  openBillUpload = () => {
    this.setState({
      record: {},
      BillUploadVisible: true,
      isUpdate: false,
    });
  };

  updateCurrentData(record) {
    this.setState({
      record,
      isUpdate: true,
      BillUploadVisible: true,
    });
  }

  handleCurrentData = record => {
    const { dispatch } = this.props;
    dispatch({
      type: 'bonds/RemoveBonds',
      payload: {
        id: record.id,
      },
      callback: res => {
        if (res.code === 1) {
          message.success('删除成功');
        }
        this.componentDidMount();
      },
    });
  };

  closeRecord(refresh) {
    const { dispatch } = this.props;
    this.setState(
      {
        BillUploadVisible: false,
      },
      () => {
        if (refresh) {
          this.componentDidMount();
        }
      }
    );
  }

  openBondsChart(res) {
    this.setState({
      ric: res.ric,
      chartTitle: res.name,
      chartVisible: true,
    });
  }

  BondsModalClose() {
    this.setState({
      chartVisible: false,
    });
  }

  /**
   *  Describe:视图
   *  Created by xjc on 2019/5/15
   */
  render() {
    const {
      loading,
      bonds: { bonds },
    } = this.props;
    const {
      listLoading,
      selectedRows,
      kVisible,
      tVisible,
      symbol,
      chart,
      codes,
      ifKline,
      BillUploadVisible,
      record,
      isUpdate,
      ric,
      chartVisible,
      chartTitle,
    } = this.state;
    let columns = [];
    const stocksList = [];
    if (columns.length === 0 && bonds.code === 1) {
      columns = this.getColumns();
    }
    const that = this;
    return (
      <PageHeaderWrapper title="债券">
        <Card>
          <Button type="primary" onClick={this.openBillUpload.bind(this, false)}>
            新增
          </Button>
          {bonds.code === 0 ? (
            <Loading />
          ) : (
            <div>
              <div style={{ margin: 8, fontSize: '1rem' }}>
                共计：{this.state.currentDataSource.length - 1}
              </div>
              <StandardTable
                bordered
                selectedRows={selectedRows}
                loading={listLoading}
                data={bonds}
                columns={columns}
                style={{ tableLayout: 'fixed' }}
                className={styles.TableLayout}
                pagination={false}
                onChange={this.handleStandardTableChange}
                scroll={{ x: 2600, y: 628 }}
                rowClassName={(record, index) =>
                  record.bondTypeToDisplay === '合计'
                    ? styles.statisticssTableBackground
                    : styles.ffffff
                }
                // onRow={record => {
                //   const res = record;
                //   return {
                //     onClick: event => {
                //       that.openBondsChart(res);
                //     },
                //   };
                // }}
                // rowKey="id"
              />
            </div>
          )}
          <BillUpload
            record={record}
            title="添加债券"
            // isRy="1"
            isUpdate={isUpdate}
            RiskDetailVisible={BillUploadVisible}
            closeRecord={this.closeRecord.bind(this)}
          />
          <Modal
            width="90%"
            title={chartTitle}
            footer=""
            destroyOnClose
            visible={chartVisible}
            centered
            onOk={this.BondsModalClose.bind(this)}
            onCancel={this.BondsModalClose.bind(this)}
          >
            {ric === null ? <Empty /> : <BondsChart ric={ric} mainId="bondEcharts" />}
          </Modal>
        </Card>
      </PageHeaderWrapper>
    );
  }

  componentDidMount() {
    const { dispatch } = this.props;

    /* 导入列表数据 */
    dispatch({
      type: 'bonds/GetBonds',
      payload: {
        bondType: 0,
        currentDataSource: this.state.currentDataSource,
      },
      callback: res => {
        this.setState({
          currentDataSource: res.list.data,
        });
      },
    });
  }

  componentWillUnmount() {
    // window.clearInterval(window.reloadData);
  }
}

export default NewTwoPosition;
